

#include"dev_w25qxx.h"

#include <stdio.h>

#include"mcu_soft_spi.h"

unt16 W25QXX_TYPE = 0;	//默认是W25Q256

SPIdevice w25qxx = { 0 };

// CS 引脚低电平有效
void W25QXX_CS_NON()
{
//#define W25QXX_CS_NON()    SPI_NSS_H(&w25qxx) 
	SPI_NSS_H(&w25qxx);
}
void W25QXX_CS_OK()
{
//#define W25QXX_CS_OK()     SPI_NSS_L(&w25qxx)
	SPI_NSS_L(&w25qxx);
}

//SPI1读写一个字节,TxData要写入的字节,返回读取到的字节
unt8 SPI_ReadWriteByte(unt8 TxData)
{
	return 0; //	Soft_SPI_RW0_CPOL_0_CPHA_0(&w25qxx, TxData);
}

// 如果可以，用硬件实现spi数组读写速度会更快。
void SPI_ReadBytes(unt8* buf, int len)
{
	for (int i = 0; i < len; i++) {
		buf[i] = SPI_ReadWriteByte(0xFF);
	}
}
void SPI_WriteBytes(unt8* buf, int len)
{
	for (int i = 0; i < len; i++) {
		SPI_ReadWriteByte(buf[i]);
	}
}


//////////////   上面是硬件接口            /////////////////////////////


/**
  * @brief
  * @param
  * @param
  * @retval None
  */
unt8 W25QXX_Init(void)
{
	unt8 temp;


	W25QXX_TYPE = W25QXX_ReadID();	        //读取FLASH ID.
	switch (W25QXX_TYPE)
	{
	case W25Q80:
	{
		printfs("W25Q80 \r\n");
		temp = W25Q_OK;
		break;
	}
	case W25Q16:
	{
		printfs("W25Q16 \r\n");
		temp = W25Q_OK;
		break;
	}
	case W25Q32:
	{
		printfs("W25Q32 \r\n");
		temp = W25Q_OK;
		break;
	}
	case W25Q64:
	{
		printfs("W25Q64 \r\n");
		temp = W25Q_OK;
		break;
	}
	case W25Q128:
	{
		printfs("W25Q128 \r\n");
		temp = W25Q_OK;
		break;
	}
	case W25Q256:
	{
		printfs("W25Q256 \r\n");
		temp = W25QXX_Read_SR(3);            //读取状态寄存器3，判断地址模式
		if ((temp & 0X01) == 0)			          //如果不是4字节地址模式,则进入4字节地址模式
		{
			W25QXX_CS_OK(); 			            //选中
			SPI_ReadWriteByte(W25X_Enable4ByteAddr);//发送进入4字节地址模式指令   
			W25QXX_CS_NON();       		        //取消片选   
		}
		temp = W25Q_OK;
		break;
	}
	default:
		temp = W25Q_ERROR;
		break;
	}
	return temp;
}

//读取W25QXX的状态寄存器，W25QXX一共有3个状态寄存器
//状态寄存器1：
//BIT7  6   5   4   3   2   1   0
//SPR   RV  TB BP2 BP1 BP0 WEL BUSY
//SPR:默认0,状态寄存器保护位,配合WP使用
//TB,BP2,BP1,BP0:FLASH区域写保护设置
//WEL:写使能锁定
//BUSY:忙标记位(1,忙;0,空闲)
//默认:0x00
//状态寄存器2：
//BIT7  6   5   4   3   2   1   0
//SUS   CMP LB3 LB2 LB1 (R) QE  SRP1
//状态寄存器3：
//BIT7      6    5    4   3   2   1   0
//HOLD/RST  DRV1 DRV0 (R) (R) WPS ADP ADS
//regno:状态寄存器号，范:1~3
//返回值:状态寄存器值
unt8 W25QXX_Read_SR(unt8 regno)
{
	unt8 byte = 0, command = 0;
	switch (regno)
	{
	case 1:
		command = W25X_ReadStatusReg1;    //读状态寄存器1指令
		break;
	case 2:
		command = W25X_ReadStatusReg2;    //读状态寄存器2指令
		break;
	case 3:
		command = W25X_ReadStatusReg3;    //读状态寄存器3指令
		break;
	default:
		command = W25X_ReadStatusReg1;
		break;
	}
	W25QXX_CS_OK();                           //使能器件   
	SPI_ReadWriteByte(command);            //发送读取状态寄存器命令    
	byte = SPI_ReadWriteByte(0Xff);          //读取一个字节  
	W25QXX_CS_NON();                          //取消片选     
	return byte;
}

//写W25QXX状态寄存器
void W25QXX_Write_SR(unt8 regno, unt8 sr)
{
	unt8 command = 0;
	switch (regno)
	{
	case 1:
		command = W25X_WriteStatusReg1;    //写状态寄存器1指令
		break;
	case 2:
		command = W25X_WriteStatusReg2;    //写状态寄存器2指令
		break;
	case 3:
		command = W25X_WriteStatusReg3;    //写状态寄存器3指令
		break;
	default:
		command = W25X_WriteStatusReg1;
		break;
	}
	W25QXX_CS_OK();                            //使能器件   
	SPI_ReadWriteByte(command);            //发送写取状态寄存器命令    
	SPI_ReadWriteByte(sr);                 //写入一个字节  
	W25QXX_CS_NON();                             //取消片选     	      
}
//W25QXX写使能	
//将WEL置位   
void W25QXX_Write_Enable(void)
{
	W25QXX_CS_OK();                            //使能器件   
	SPI_ReadWriteByte(W25X_WriteEnable);   //发送写使能  
	W25QXX_CS_NON();                             //取消片选     	      
}
//W25QXX写禁止	
//将WEL清零  
void W25QXX_Write_Disable(void)
{
	W25QXX_CS_OK();                            //使能器件   
	SPI_ReadWriteByte(W25X_WriteDisable);  //发送写禁止指令    
	W25QXX_CS_NON();                             //取消片选     	      
}
//读取芯片ID
//返回值如下:				   
//0XEF13,表示芯片型号为W25Q80  
//0XEF14,表示芯片型号为W25Q16    
//0XEF15,表示芯片型号为W25Q32  
//0XEF16,表示芯片型号为W25Q64 
//0XEF17,表示芯片型号为W25Q128 	  
//0XEF18,表示芯片型号为W25Q256
unt16 W25QXX_ReadID(void)
{
	unt16 Temp = 0;
	W25QXX_CS_OK();
	SPI_ReadWriteByte(0x90);//发送读取ID命令	    
	SPI_ReadWriteByte(0x00);
	SPI_ReadWriteByte(0x00);
	SPI_ReadWriteByte(0x00);
	Temp |= SPI_ReadWriteByte(0xFF) << 8;
	Temp |= SPI_ReadWriteByte(0xFF);
	W25QXX_CS_NON();
	return Temp;
}
//读取SPI FLASH  
//在指定地址开始读取指定长度的数据
//pBuffer:数据存储区
//ReadAddr:开始读取的地址(24bit)
//NumByteToRead:要读取的字节数(最大65535)
void W25QXX_Read(unt8* pBuffer, unt32 ReadAddr, unt16 NumByteToRead)
{
	unt16 i;
	W25QXX_CS_OK();                            //使能器件   
	SPI_ReadWriteByte(W25X_ReadData);      //发送读取命令  
	if (W25QXX_TYPE == W25Q256)                //如果是W25Q256的话地址为4字节的，要发送最高8位
	{
		SPI_ReadWriteByte((unt8)((ReadAddr) >> 24));
	}
	SPI_ReadWriteByte((unt8)((ReadAddr) >> 16));   //发送24bit地址    
	SPI_ReadWriteByte((unt8)((ReadAddr) >> 8));
	SPI_ReadWriteByte((unt8)ReadAddr);

	SPI_ReadBytes(pBuffer, NumByteToRead);
	//for (i = 0; i < NumByteToRead; i++)
	//{
	//	pBuffer[i] = SPI_ReadWriteByte(0XFF);    //循环读数  
	//}

	W25QXX_CS_NON();
}
//SPI在一页(0~65535)内写入少于256个字节的数据
//在指定地址开始写入最大256字节的数据
//pBuffer:数据存储区
//WriteAddr:开始写入的地址(24bit)
//NumByteToWrite:要写入的字节数(最大256),该数不应该超过该页的剩余字节数!!!	 
void W25QXX_Write_Page(unt8* pBuffer, unt32 WriteAddr, unt16 NumByteToWrite)
{
	unt16 i;

	W25QXX_Write_Enable();                  //SET WEL 
	W25QXX_CS_OK();                           //使能器件   
	SPI_ReadWriteByte(W25X_PageProgram);   //发送写页命令   
	if (W25QXX_TYPE == W25Q256)                //如果是W25Q256的话地址为4字节的，要发送最高8位
	{
		SPI_ReadWriteByte((unt8)((WriteAddr) >> 24));
	}
	SPI_ReadWriteByte((unt8)((WriteAddr) >> 16)); //发送24bit地址    
	SPI_ReadWriteByte((unt8)((WriteAddr) >> 8));
	SPI_ReadWriteByte((unt8)WriteAddr);

	SPI_WriteBytes(pBuffer, NumByteToWrite);

	//for (i = 0; i < NumByteToWrite; i++) {
	//	SPI_ReadWriteByte(pBuffer[i]);//循环写数  
	//}

	W25QXX_CS_NON();                             //取消片选 
	W25QXX_Wait_Busy();					   //等待写入结束
}


//无检验写SPI FLASH 
//必须确保所写的地址范围内的数据全部为0XFF,否则在非0XFF处写入的数据将失败!
//具有自动换页功能 
//在指定地址开始写入指定长度的数据,但是要确保地址不越界!
//pBuffer:数据存储区
//WriteAddr:开始写入的地址(24bit)
//NumByteToWrite:要写入的字节数(最大65535)
//CHECK OK
void W25QXX_Write_NoCheck(unt8* pBuffer, unt32 WriteAddr, unt16 NumByteToWrite)
{
	unt16 pageremain;

	pageremain = 256 - WriteAddr % 256; //单页剩余的字节数		 	    
	if (NumByteToWrite <= pageremain)pageremain = NumByteToWrite;//不大于256个字节
	while (1)
	{
		W25QXX_Write_Page(pBuffer, WriteAddr, pageremain);
		if (NumByteToWrite == pageremain)break;//写入结束了
		else //NumByteToWrite>pageremain
		{
			pBuffer += pageremain;
			WriteAddr += pageremain;

			NumByteToWrite -= pageremain;			  //减去已经写入了的字节数
			if (NumByteToWrite > 256)pageremain = 256; //一次可以写入256个字节
			else pageremain = NumByteToWrite; 	  //不够256个字节了
		}
	};
}
//




//擦除整个芯片		  
//等待时间超长...
void W25QXX_Erase_Chip(void)
{
	W25QXX_Write_Enable();                     //SET WEL 
	W25QXX_Wait_Busy();
	W25QXX_CS_OK();                              //使能器件   
	SPI_ReadWriteByte(W25X_ChipErase);        //发送片擦除命令  
	W25QXX_CS_NON();                             //取消片选     	      
	W25QXX_Wait_Busy();   				             //等待芯片擦除结束
}
//擦除一个扇区
//Dst_Addr:扇区地址 根据实际容量设置，扇区的序号。函数里已经Dst_Addr*=4096了。
//擦除一个扇区的最少时间:150ms
void W25QXX_Erase_Sector(unt32 Dst_Addr)
{
	//监视falsh擦除情况,测试用   
	//printfs("fe:%x\r\n",Dst_Addr);	  
	Dst_Addr *= 4096;
	W25QXX_Write_Enable();                  //SET WEL 	 
	W25QXX_Wait_Busy();
	W25QXX_CS_OK();                           //使能器件   
	SPI_ReadWriteByte(W25X_SectorErase);   //发送扇区擦除指令 
	if (W25QXX_TYPE == W25Q256)                //如果是W25Q256的话地址为4字节的，要发送最高8位
	{
		SPI_ReadWriteByte((unt8)((Dst_Addr) >> 24));
	}
	SPI_ReadWriteByte((unt8)((Dst_Addr) >> 16));  //发送24bit地址    
	SPI_ReadWriteByte((unt8)((Dst_Addr) >> 8));
	SPI_ReadWriteByte((unt8)Dst_Addr);
	W25QXX_CS_NON();                           //取消片选     	      
	W25QXX_Wait_Busy();   				           //等待擦除完成
}
//等待空闲
#define  sFLASH_CMD_RDSR           0x05  /*!< Read Status Register1 instruction  */
void W25QXX_Wait_Busy(void)
{
	//	while((W25QXX_Read_SR(1)&0x01)==0x01);   // 等待BUSY位清空

	unt8 flashstatus = 0;
	/*!< Select the FLASH: Chip Select low */
	W25QXX_CS_OK();
	/*!< Send "Read Status Register" instruction */
	SPI_ReadWriteByte(sFLASH_CMD_RDSR);
	/*!< Loop as long as the memory is busy with a write cycle */
	do
	{
		/*!< Send a dummy byte to generate the clock needed by the FLASH
		and put the value of the status register in FLASH_Status variable */
		flashstatus = SPI_ReadWriteByte(0xFF);
	} while ((flashstatus & 0x01) == 0x01); /* Write in progress */
	/*!< Deselect the FLASH: Chip Select high */
	W25QXX_CS_NON();


}

//获取状态 (1,忙;0,空闲)
unt8 W25QXX_Get_State(void)
{
	unt8 temp;
	temp = W25QXX_Read_SR(1);
	temp = temp & 0x01;
	return temp;
}
//进入掉电模式
void W25QXX_PowerDown(void)
{
	W25QXX_CS_OK();                            //使能器件   
	SPI_ReadWriteByte(W25X_PowerDown);      //发送掉电命令  
	W25QXX_CS_NON();                           //取消片选     	      
	mcu_delay_ms(3);                            //等待TPD  
}
//唤醒
void W25QXX_WAKEUP(void)
{
	W25QXX_CS_OK();                                //使能器件   
	SPI_ReadWriteByte(W25X_ReleasePowerDown);   //  send W25X_PowerDown command 0xAB    
	W25QXX_CS_NON();                               //取消片选     	      
	mcu_delay_ms(3);                                //等待TRES1
}


